<?php 
/**
 * 拼团活动
 * @Author buddha
 */

namespace Shop\Controller;

class JoinController extends CommonController
{
	/**
	 * 过滤条件
	 * @author buddha <[email address]>
	 * @return [type] [description]
	 */
	public function index( $keywords='',$status='',$time_status='' ){
		//活动状态
		if ($status == '') {
			$map['status'] = array('egt',0);
		}else{
			$map['status'] = $status;
		}
		//活动时间状态
		if (!empty($time_status)) {
			switch ($time_status) {
				case '1':
					$map['stime'] = array('gt',NOW_TIME);
					break;
				case '2':
					$map['etime'] = array('elt',NOW_TIME);
					break;
				default:
					$map['etime'] = array('gt',NOW_TIME);
					break;
			}
		}
		//关键字
		if(!empty($keywords))$map['name'] = array('LIKE', '%'.$keywords.'%');
      //查询活动店铺等级
	    $grade_id = M('Store')->where('store_id='.$this->store_id)->getField('grade_id');
      $map['_string'] = "FIND_IN_SET($grade_id,store_level)";
	    parent::index($map);
	}

	/**
	 * 展示列表前格式化数据
	 * @author buddha <[email address]>
	 * @param  [type] &$lists [description]
	 * @return [type]         [description]
	 */
	public function _before_index_display( &$lists ){
		foreach ($lists as $key => $value) {
			$lists[$key]['limit'] = ($value['limit'] > 0) ? $value['limit'].'分钟' : ''; 
			//判断拼团活动是否下单
			$is_join = M('Join_list')->where('activity_id='.$value['id'])->count();
			$lists[$key]['is_join'] = ($is_join > 0) ? 1 : 0;
            //判断此店铺是否有参团商品
            $store_item_id = array_filter( explode(',',$value['item_ids']) );
            if (!empty($store_item_id)) {
                $newItemIds = array();
                foreach ($store_item_id as $k => $v) {
                    if (M('Item')->where('id='.$v)->getField('store_id') == $this->store_id) {
                        $newItemIds[] = $v;
                    }
                }
                $lists[$key]['item_ids'] = implode(',',$newItemIds);
            }
		}
	}

	/**
	 * 查看或者添加拼团商品 页面展示
	 * @author buddha <[email address]>
	 * @return [type]       [description]
	 */
	public function joinItem(){
		$type = I('get.type') ?: 'edit';
		$id = I('get.id');
		if (empty($id)) $this->error('参数错误！');
		//编辑商品
		$tpl = ($type == 'edit') ? 'edit' : 'itemList'; 
		if ($type != 'edit') {
			//拼团商品 商户ID
			$item_ids = M('Item')->where(array('store_id'=>$this->store_id))->getField('id',true);
			$prefix = C('DB_PREFIX');
	        $l_table = $prefix.'join_item';
	        $r_table = $prefix.'item';
			$model =  M()->table($l_table.' j')->join($r_table.' m ON j.item_id = m.id');
			$field = 'm.images,m.store_id,m.name,m.number,j.item_id as id,j.price,j.stock,j.status,j.join_num,j.first_price,j.join_price';
			$order = 'j.item_id DESC';
			$where = array(
					'j.join_id' => $id,
					'j.status'  => array('egt',0),
					'j.item_id' => array('IN',$item_ids),
				);
			//搜索功能
			if (I('keywords')) {
				$where['m.name|m.number'] = array('LIKE','%'.I('keywords').'%');
			}
			$items = $this->lists($model,$where,$order,$field,10,null);
			int_to_string($items,array('status' => array('0' => '<span class="text-cancel">上架</span>', '1' => '<span class="text-success">下架</span>')));
			$this->lists = $items;
		}
		$this->join_id = $id;
		$this->display($tpl);
	}

	/**
	 * 编辑拼团商品 页面展示
	 * @author buddha <[email address]>
	 * @return [type] [description]
	 */
	public function editItem(){
		$id = I('id');
        $joinId = I('join_id');
        if(empty($id) || empty($joinId)) $this->error('参数异常');
        $prefix = C('DB_PREFIX');
        $joinItemMode = $prefix.'join_item';
        $joinItemSpecMode = $prefix.'join_item_spec';
        $itemModel = $prefix.'item';
        $model = M('join j')->join(' INNER JOIN '.$joinItemMode.' m ON j.id = m.join_id ')
                            ->join(' LEFT JOIN '.$joinItemSpecMode.' s ON s.item_id = m.item_id ')
                            ->join(' LEFT JOIN '.$itemModel.' i ON i.id=m.item_id');
        $map['m.item_id'] = array('eq',$id);
        $map['m.join_id'] = array('eq',$joinId);
        $field = 'j.id as join_id,m.prop_info,m.item_id,m.price as oprice,m.stock as ostock,m.join_num,m.first_price ofprice,m.join_price as ojprice,s.spc_code,i.cid_1,i.cid_2,i.cid_3,i.name,i.price,i.stock';
        $data = $model->where($map)->field($field)->find();
        $data['prop_info'] = json_decode($data['prop_info'],true);
        $this->data = $data;
		$this->display();
	}

	/**
	 * 拼团商品添加 处理方法
	 * @author buddha <[email address]>
	 * @return [type] [description]
	 */
    public function itemAdd(){
    	$join_id = I('join_id');
    	$item_ids = I('item_ids');
    	if (empty($join_id)) $this->error('参数错误！');
    	if (empty($item_ids)) $this->error('请选择商品！');
    	// 此拼团活动商品id集合
    	$itemIds = array_filter( explode(',',M('Join')->where('id='.$join_id)->getField('item_ids')));
    	$newIds = explode(',',$item_ids);
        //开启事务
        $model = M('Join');
        $model->startTrans();
    	$res = $this->delItemIds($join_id,$itemIds,$newIds,$model);
    	//将添加商品加入拼团商品表
    	$ret = $this->addItemToJoin($join_id,$newIds);
    	if ($res && $ret) {
            $model->commit();
    		$this->success('添加成功！',U('Join/joinItem',array('type'=>'item','id'=>$join_id)),3);
    	}else{
            $model->rollback();
    		$this->error('添加失败！');
    	}
    }

  	/**
  	 * 拼团商品内容 处理方法
  	 * @author buddha <[email address]>
  	 * @return [type] [description]
  	 */
  	public function editItemHandle(){
          $Model = D('Admin/JoinItem');
          $item_id = I('item_id');
          //验证库存
          if (I('post.stock') > I('post.old_stock')) {
            $this->error('库存设置不能大于商品总库存!');
          }
          if (I('post.spc_quantity') && (array_sum(I('post.spc_quantity')) > I('post.old_stock') ) ) {
            $this->error('库存设置不能大于商品总库存!');
          }
          //验证拼团人数设置
          if (I('post.join_num') > I('post.stock')) {
            $this->error('参团人数不能大于设置的库存!');
          }
          //检验是否存在规格 且规格是否设置
          $result = $this->checkItemProp($item_id);
          if ($result == 0) {
            $this->error('此商品规格还未设置或者设置参数有误!');
          }
          $Model->startTrans();
          $res = $Model->update();
          if($res !== false){
              $rst = $this->saveSpecifiction($item_id);
              if($rst !== false){
                  $Model->commit();
                  $this->success('更新成功' , U('Join/joinItem' ,array('type'=>'item','id' => $_POST['join_id'])));
              }else{
                  $Model->rollback();
                  $this->error('更新失败');
              }
          }else{
              $Model->rollback();
              $this->error($Model->getError());
          }
    }

    /**
     * 拼团商品规格、价格处理
     * @author buddha <[email address]>
     * @param  [type] $item_id [description]
     * @return [type]          [description]
     */
    public function saveSpecifiction($item_id = null){
        if(empty($item_id)){
            return false;
        }
        //实例化商品规格模型
        $ItemSpecifiction = M('JoinItemSpec');
        //获取库存数量数组
        $spc_quantity = I('spc_quantity');
        $activity_id  = I('join_id'); 
        //获取价格数组
        $first_price = I('first_pri');
        //获取库存数量数组
        $join_price = I('join_pri');
        //生成规格组合值数组
        $total_quantity = 0;
        foreach($spc_quantity as $key => $val){
            if(!empty($val)){
                $spcItem[] = array(
                        'item_id' => $item_id,
                        'spc_code'  => $key,
                        'quantity'  => $val,
                        'first_price'  => $first_price[$key],
                        'join_price'  => $join_price[$key],
                        'activity_id' => $activity_id ,
                );
                //计算总库存
                $total_quantity += $spc_quantity[$key];
            }
        }
        $spe = M('ItemSpecifiction')->where(array('item_id'=>$item_id))->select();
        if($spe){
            if(!$spcItem){
                $this->error('请填写商品规格价格');
            }
        }
        //清空旧的规格数据
        $result = $ItemSpecifiction->where('item_id='.$item_id.' and activity_id='.$activity_id)->delete();
        if($result !== false){
            //规格组合信息批量写入
            if(!empty($spcItem)){
                if($result = $ItemSpecifiction->addAll($spcItem)){
                    //更新总库存
                    $result = M('JoinItem')->where(array('item_id'=>$item_id ,'join_id' => $activity_id))->setField('stock', $total_quantity);
                }
            }
        }
        return $result;       
    }

  	/**
  	 * 设置拼团商品状态
  	 * @author buddha <[email address]>
  	 */
  	public function setItemStatus(){
  		$ids = (array)I('request.ids');
          $joinId = I('request.join_id');
          $status = I('request.status');
          if(empty($ids) || empty($joinId)){
              $this->error('请选择要操作的数据');
          }
          $joinData = M('Join')->where(array('id'=>$joinId))->find();
          $joinItemIds = explode(',',$joinData['item_ids']);
          $model = M('JoinItem');
          $map['item_id'] = array('in',$ids);
          $map['join_id'] = array('eq',$joinId);
          $model->startTrans();
          switch ($status){
              case -1 ://删除
                  $rst = $model->where($map)->delete();
                  if($rst !== false){
                      $rst = $this->delItemIds($joinId,$joinItemIds,$ids);
                      if($rst !== false){
                          $model->commit();
                          $this->success('删除成功','',IS_AJAX);
                      }else{
                          $model->rollback();
                          $this->error('删除失败','',IS_AJAX);
                      }
                  }else{
                      $model->rollback();
                      $this->error('删除失败','',IS_AJAX);
                  }
              break;
              case 0  :  //下架
                  $rst = $model->where($map)->save(array('status'=>$status));
                  if($rst !== false){
                      $model->commit();
                      $this->success('下架成功','',IS_AJAX);
                  }else{
                      $model->rollback();
                      $this->error('下架失败','',IS_AJAX);
                  }
              break;
              case 1  :  //上架
                  $rst = $model->where($map)->save(array('status'=>$status));
                  if($rst !== false){
                      $model->commit();
                      $this->success('上架成功','',IS_AJAX);
                  }else{
                      $model->rollback();
                      $this->error('上架失败','',IS_AJAX);
                  }
              break;
              default:
                  $model->rollback();
                  $this->error('系统参数错误');
              break;
              
          }
  	}

    /**
     * 拼团订单列表
     * @author buddha <[email address]>
     * @return [type] [description]
     */
    public function orderList(){
          $id = I('id');
          if(!$id)$this->error('参数错误！');
          $prefix  = C('DB_PREFIX');
          $model    = M()->table( $prefix.'join_list a ' )->join ('INNER JOIN '. $prefix.'item b on a.item_id=b.id ' );
          $order  = 'a.id desc' ;
          $fields = 'a.* , b.thumb,b.number ,b.name';
          $item_ids = M('Item')->where(array('store_id'=>$this->store_id))->getField('id',true);
          $where = array(
                    'a.activity_id' => $id,
                    'a.item_id' => array('IN',$item_ids),
                );
          //搜索条件
          if (I('status') != '') {
              $where['a.status'] = I('status');
          }
          $lists  = A('Home/Page', 'Event')->lists($model, $where, $order, 15 ,NULL,$fields);
          $this->assign('list' ,$lists);
          $this->join_id = $id;
          $this->display();
    }

    /**
     * 拼团订单详情
     * @author buddha <[email address]>
     * @return [type] [description]
     */
    public function joinView(){
          $main = M('Join_list')->where('id='.I('id'))->find();
          $this->main = $main ;
          $data = M('Join_order')->alias('a')->join('__PAYMENT__ b on a.payment_id=b.id')->where('a.join_id='.I('id'))->field('a.* , b.payment_status ,b.payment_type')->select();
          foreach($data as $k => $v){
            $data[$k]['spec'] = unserialize($v['spec']);
          }
          $this->count = M('Join_order')->where('join_id='.I('id'))->count();
          $this->data  = $data ;
          $this->display();
    }

  	/**
  	 * 添加或者删除拼团商品
  	 * @author buddha <[email address]>
  	 * @param  [type] $id      [description]
  	 * @param  [type] $itemIds [description]
  	 * @param  [type] $newIds  [description]
  	 * @return [type]          [description]
  	 */
  	public function delItemIds($id,$itemIds,$newIds,$model = 'Join'){
          $newArr = array();
          if (!empty($itemIds)) {
              $newArr = $itemIds;
          	foreach ($newIds as $key=>$val){
  	            if(!in_array($val,$itemIds)){
  	                array_push($newArr,$val);
  	            }
          	}
          }else{
          	$newArr = $newIds;
          }
          $Ids = implode(',',$newArr);
          $rst =$model->where(array('id'=>$id))->save(array('item_ids'=>$Ids));
          return $rst;
    }

    /**
     * 拼团商品加入
     * @author buddha <[email address]>
     * @param  [type] $item_ids [description]
     */
    public function addItemToJoin( $join_id, $item_ids ){
    	if (empty($item_ids) || empty($join_id)) {
    		return false;
    	}
    	$info = M('Join')->where('id='.$join_id)->field('stime,etime')->find();
    	$data = array();
    	foreach ($item_ids as $key => $item_id) {
            $price = M('Item')->where(array('id'=>$item_id))->getField('price');
            $data[$key]['item_id'] = $item_id;
    		$data[$key]['stime'] = $info['stime'];
    		$data[$key]['etime'] = $info['etime'];
    		$data[$key]['join_id'] = $join_id;
            $data[$key]['price'] = $price;
            $data[$key]['stock'] = 2 ;
            $data[$key]['join_num'] = 2 ;
    	}
    	return M('JoinItem')->addAll($data);
    }

    /**
     * 输出商品属性，供前端AJAX调用
     * @param string $item_id
     * @param string $type
     * @param string $cid_1
     * @param string $cid_2
     * @param string $cid_3
     */
    public function ajaxProp($item_id = null, $type = null, $cid_1 = null, $cid_2 = null, $cid_3 = null ,$activity_id = null){
        $where['type'] = $type;
        if(!empty($cid_1)){
            $cid[0] = $cid_1;
        }
    
        if(!empty($cid_2)){
            $cid[1] = $cid_2;
        }
    
        if(!empty($cid_3)){
            $cid[2] = $cid_3;
        }
    
        $where['cid'] = array('in',$cid);
        $where['a.item_id'] = array('eq',$item_id);
        $where['b.type'] = array('eq','specification');
        
        //获取该商品的属性值和关联的属性项信息（关联模型不能用从表的字段排序，用原生sql代替）
        $prefix = C('DB_PREFIX');
        $l_table = $prefix.'item_extend';
        $r_table = $prefix.'item_property';
        $field = 'b.type, b.cname, b.ename, b.displayorder, b.formtype, a.*';
        $order = 'b.displayorder asc, b.id asc';
        $model = M()->table($l_table.' a')->join($r_table.' b ON a.prp_id = b.id');
        $property_list = $model->where($where)->field($field)->order($order)->select();
        //获取规格组合数据
        $spc_data = null;
        $propVal = array();
        if(!empty($item_id)){
            $field = 'spc_code,quantity,first_price,join_price';
            $spc_info = M('join_item_spec')->where('item_id = '.$item_id.' and activity_id='.$activity_id)->field($field)->select();
            if(!empty($spc_info)){
                $spc_data = json_encode($spc_info);
                foreach ($spc_info as $key=>$val){
                    $propVal = array_merge($propVal,explode('-',$val['spc_code']));
                }
            }
        }
        //拼接属性名称，属性选项配置，属性值数组
        if($property_list){
            foreach($property_list as $list) {
                $property_all[$list['id']]['property'] = $list;
                $property_all[$list['id']]['option'] = $this->getOptionValue(unserialize($list['info']),$list['type']);
                $property_all[$list['id']]['value'] = $propVal;
            }
        }
        $this->assign('item_id', $item_id);
        $this->assign('type', $type);
        $this->assign('property_all', $property_all);
        $this->assign('spc_data', $spc_data);
        $this->display();
    }

    /**
     * 获取商品属性选项配置值
     * @author ezhu <ezhu@jipu.com>
     */
    public function getOptionValue($item_info = null, $formtype = null){
      $returnInfo = array();
      $pic_path = array();
  
      if($item_info && is_array($item_info)){
          if($formtype === 'color'){
              $pic = $item_info['pic'];
  
              if($pic && is_array($pic)){
                  foreach($pic as $k => $v) {
                      if($v){
                          $pic_path[] = get_cover($v, 'path');
                      } else{
                          $pic_path[] = null;
                      }
                  }
              }
          }
  
          $property = $item_info['property'];
          if($property && is_array($property)){
              foreach($property as $key => $val) {
                  if($val && is_array($val)){
                      $i = 0;
                      foreach($val as $k => $v) {
                          $option = $this->getOptionByCode($v);
  
                          if($formtype === 'color'){
                              $option['item_pic'] = $pic_path[$i];
                              $i++;
                          }
  
                          $returnInfo[] = $option;
                      }
                  } else{
                      if($formtype === 'input' || $formtype === 'textarea'){
                          $returnInfo[] = $val;
                      }else{
                          $returnInfo[] = $this->getOptionByCode($val);
                      }
                  }
              }
          }
      }
      return $returnInfo;
    }
  
   /**
    * 输出商品属性选项值
    * @author Max.Yu <max@jipu.com>
    */
    public function getOptionByCode($code){
  
      $returnInfo = array();
  
      //实例化属性选项模型
      $PropertyOption = M('PropertyOption');
  
      //定义返回或者操作的字段
      $field = '*';
  
      //查询条件初始化
      $where['code'] = $code;
  
      //获取属性选项值列表
      $returnInfo = $PropertyOption->where($where)->field($field)->find();
  
      return $returnInfo;
    }

    /**
     * 检查商品是否存在规格
     * @author buddha <[email address]>
     * @param  [type] $item_id [description]
     * @return [type]          [description]
     */
    public function checkItemProp( $item_id ){
      $cids = M('Item')->where('id='.$item_id)->field('cid_1,cid_2,cid_3')->find();
      $ids = array_values($cids);
      $map = array('op.type'=>'specification','op.cid'=>array('IN',$ids),'oe.item_id'=>array('eq',$item_id));
      $spc = M('ItemProperty')->alias('op')->join('LEFT JOIN __ITEM_EXTEND__ oe ON op.id = oe.prp_id')->where($map)->field('op.ename,op.cname')->select(); 
      if ($spc) {
        //获取价格数组
        $first_price = I('first_pri');
        //获取库存数量数组
        $join_price = I('join_pri');
        $join_stock = I('spc_quantity');
        $a = array_values($first_price);
        $b = array_values($join_price);
        $c = array_values($join_stock);
        //$arr = array_merge($a,$b,$c);
        if ( arr2str($c) == '' || in_array(0,$c) || strstr(arr2str($c),'-')) {
           return 0;
        }else{
          return 1; 
        }
      }else{
        return 1;
      }
    }
    
}

 ?>